package ArrayList;

import LinkList02.MySingleList;

import javax.sound.midi.Soundbank;
import javax.swing.*;
import java.util.List;

public class MyLinkedList {
    static class ListNode{
        private int val;
        private ListNode prev;
        private ListNode next;

        public ListNode(int val){
            this.val = val;
        }
    }

    public ListNode head;
    public ListNode last;
    //求链表长度
    public int size(){
        int count = 0;
        ListNode cur = head;
        while(cur != null){
            cur = cur.next;
            count++;
        }
        return count;
    }

    //展示链表

    public void show(){
        ListNode cur = head;
        while(cur != null){
            System.out.print(cur.val + " ");
            cur =  cur.next;
        }
        System.out.println();
    }


    //查找元素key是否在链表当中存在,并返回下标
    public boolean contains(int key){
        ListNode cur = head;
        while(cur != null){
            if(cur.val ==  key){
                return true;
            }
        }
        return false;
    }













    //头插法
    public void addFirst(int data){
        ListNode node =  new ListNode(data);
        if(head == null){
            head = node;
            last = node;
        }else{
            node.next = head;
            head.prev = node;
            head  =  node;
        }

    }


    //尾插法
    public void addLast(int data){
       ListNode node = new ListNode(data);
       if(head == null){
           head = node;
           last  = node;
       }else{
           last.next = node;
           node.prev = last;
           last = node;
       }
    }

    //返回下标所对应的元素]
    public ListNode searchIndex(int index){
        ListNode cur = head;
        while(index != 0){
            cur = cur.next;
            index--;
        }
        return cur;
    }


    //在任意位置插入元素
    public void addIndex(int index, int data){
        if(index  < 0 || index >size()){
            System.out.println("index 输入不合法,请重新输入");
            return ;
        }
        if(index == 0){
            addFirst(data);
        }
        if(index == size()){
            addLast(data);
        }
        ListNode p = searchIndex(index);
        ListNode s = new ListNode(data);
        s.next = p ;
        p.prev.next = s;
        s.prev = p.prev;
        p.prev = s;

    }
}